package com.lagou.edu.service.impl;

import com.lagou.edu.bean.ToEmail;
import com.lagou.edu.dao.LagouAuthCodeDao;
import com.lagou.edu.entity.LagouAuthCode;
import com.lagou.edu.service.CodeService;
import com.lagou.edu.service.EmailDubboService;
import com.lagou.edu.service.UserDubboService;
import com.lagou.edu.util.VerifyUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author zhangjinshan
 * @version 1.0
 * @description
 * @date 2021/9/1 上午10:41
 */
@Service
public class CodeServiceImpl implements CodeService {

    /**
     * 验证码过期时间
     */
    private Long codeExpireTime = 3L;

    @Autowired
    private LagouAuthCodeDao lagouAuthCodeDao;

    @Reference(check = false)
    private EmailDubboService emailDubboService;

    @Reference(check = false)
    private UserDubboService userDubboService;


    @Override
    public boolean create(String email) {
        if (userDubboService.isRegister(email)) {
            return false;
        }
        // 保存验证码
        String code = VerifyUtil.createCode();
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setCode(code);
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCreatetime(new Date());
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(codeExpireTime);
        lagouAuthCode.setExpiretime(Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()));
        lagouAuthCodeDao.save(lagouAuthCode);
        // 发送邮件
        ToEmail toEmail = new ToEmail();
        toEmail.setTos(new String[]{email});
        toEmail.setSubject("注册验证码");
        toEmail.setContent("验证码：" + code);
        return emailDubboService.sendEmail(toEmail);
    }
}
